// import { resolve } from 'path';
import { useZhichengStore } from '../store/index';
const ZhichengStore = useZhichengStore();
// const fs = require('fs');

// function pathResolve(dir: string) {
//   return resolve(process.cwd(), '.', dir);
// }

export const getFolder = (path: any) => {
  const components: Array<string> = [];
  const files = fs.readdirSync(path);
  files.forEach(function (item: string) {
    const stat = fs.lstatSync(path + '/' + item);
    if (stat.isDirectory() === true && item != 'components') {
      components.push(path + '/' + item);
      components.push(pathResolve(path + '/' + item));
    }
  });
  return components;
};
// 数组去重
export const unique = (_arr) => {
  return _arr.filter(function (item, index) {
    return _arr.indexOf(item) === index;
  });
};
// base64 转buffer
export function dataURItoBuffer(dataURI) {
  const byteString = atob(dataURI.split(',')[1]);
  const buffer = new ArrayBuffer(byteString.length);
  const view = new Uint8Array(buffer);

  for (let i = 0; i < byteString.length; i++) {
    view[i] = byteString.charCodeAt(i);
  }

  return buffer;
}
// base64转blob、
export function dataURItoBlob(dataURI) {
  const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
  const buffer = dataURItoBuffer(dataURI);
  return new Blob([buffer], {
    type: mimeString,
  });
}

// 日期格式化
export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null;
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}';
  let date;
  if (typeof time === 'object') {
    date = time;
  } else {
    if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
      time = parseInt(time);
    } else if (typeof time === 'string') {
      time = time
        .replace(new RegExp(/-/gm), '/')
        .replace('T', ' ')
        .replace(new RegExp(/\.[\d]{3}/gm), '');
    }
    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  };
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value];
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value;
    }
    return value || 0;
  });
  return time_str;
}

// 密码校验（数字，小写字母，大写字母，特殊符号都至少一个；长度为8-20位；）
export const validatePass = (value, callback) => {
  const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[~!@#$%^&*\.?])[A-Za-z\d~!@#$%^&*\.?]{8,}/;
  if (value == '') {
    callback(new Error('请输入新密码'));
  } else if (value.length < 8) {
    callback(new Error('密码过于简单,长度不得低于8位!'));
  } else if (/^[0-9,]*$/.test(value)) {
    callback(new Error('密码不能纯数字!'));
  } else if (/^[a-z]+$/.test(value)) {
    callback(new Error('密码不能纯字母!'));
  } else if (/^[A-Z]+$/.test(value)) {
    callback(new Error('密码不能纯字母!'));
  } else if (!regex.test(value)) {
    callback(new Error('密码包含大写字母，小写字母，数字，特殊符号~!@#$%^&*.?四种组成!'));
  } else {
    callback();
  }
};
// 本地存储
export const LocalStorage = {
  // 设置永久缓存
  set(key: string, val: any) {
    window.localStorage.setItem(key, JSON.stringify(val));
  },
  // 获取永久缓存
  get(key: string) {
    const json: any = window.localStorage.getItem(key);
    return JSON.parse(json);
  },
  // 移除永久缓存
  remove(key: string) {
    window.localStorage.removeItem(key);
  },
  // 移除全部永久缓存
  clear() {
    window.localStorage.clear();
  },
};
export const SessionStorage = {
  // 设置临时缓存
  set(key: string, val: any) {
    window.sessionStorage.setItem(key, JSON.stringify(val));
  },
  // 获取临时缓存
  get(key: string) {
    const json: any = window.sessionStorage.getItem(key);
    return JSON.parse(json);
  },
  // 移除临时缓存
  remove(key: string) {
    window.sessionStorage.removeItem(key);
  },
  // 移除全部临时缓存
  clear() {
    window.sessionStorage.clear();
  },
  // 获取临时缓存
  getCorporationId() {
    const json: any = window.sessionStorage.getItem('userInfo');
    const data = JSON.parse(json);
    if (!data || !data.user || !data.user.corporation) {
      return '';
    }
    return data.user.corporation.corporation_id;
  },
};

export const setCookie = (name, value, day = 1) => {
  if (day !== 0) {
    // 当设置的时间等于0时，不设置expires属性，cookie在浏览器关闭后删除
    const expires = day * 24 * 60 * 60 * 1000;
    const date = new Date(+new Date() + expires);
    document.cookie = `${name}=${value};expires=${date.toUTCString()}`;
  } else {
    document.cookie = `${name}=${value}`;
  }
};
export const getCookie = (name) => {
  // 获取cookies
  const strCookie = document.cookie;
  const arrCookie = strCookie.split('; ');
  for (let i = 0; i < arrCookie.length; i++) {
    const arr = arrCookie[i].split('=');
    if (name == arr[0]) {
      return arr[1];
    }
  }
  return '';
};
// 全局弹框

export const showAlert = (isShow, message, title = '提示', delay = 3000) => {
  // 获取cookies
  ZhichengStore.changeShowAlert({ isShow, message, title, delay });
};

/** vite的特殊性, 需要处理图片 */
export const requireImg = (imgPath: string) => {
  try {
    const handlePath = imgPath.replace('@', '..');
    // https://vitejs.cn/guide/assets.html#the-public-directory
    return new URL(handlePath, import.meta.url).href;
  } catch (error) {
    console.warn(error);
  }
};
